package com.hk.core.redis.locks;

import java.util.Objects;
import java.util.concurrent.*;

/**
 * @author Kevin
 * @date 2022-11-24 23:30
 */
class JdkRedisLockRenewalStrategy implements RedisLockRenewalStrategy {

    private static final ScheduledExecutorService EXECUTOR_SERVICE;

    private static final ConcurrentHashMap<String, ScheduledFuture<?>> FUTURE_MAP;

    static {
        EXECUTOR_SERVICE = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors(),
                r -> new Thread(r, "Jdk-Redis-Lock"));
        FUTURE_MAP = new ConcurrentHashMap<>(128);
    }

    @Override
    public void renewal(String key, Runnable task, long initialDelay, long period, TimeUnit unit) {
        var scheduledFuture = EXECUTOR_SERVICE.scheduleWithFixedDelay(task, initialDelay, period, unit);
        var oldFuture = FUTURE_MAP.put(key, scheduledFuture);
        if (Objects.nonNull(oldFuture)) {
            oldFuture.cancel(true);
        }
    }

    @Override
    public void cancel(String key) {
        var scheduledFuture = FUTURE_MAP.remove(key);
        if (Objects.nonNull(scheduledFuture)) {
            scheduledFuture.cancel(true);
        }
    }

    @Override
    public void shutdown() {
        EXECUTOR_SERVICE.shutdown();
    }
}
